package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.iot08.common.entity.app.DeviceLocationOriginalRecord;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author cwj
 * @description
 * @date 2025/6/7 9:53
 **/
@Slf4j
@Service
public class DeviceLocationOriginalRecordService extends BaseService<DeviceLocationOriginalRecord> {


    /**
     * @description 保存
     * @author cwj
     * @param [imei, message]
     * @return void
     * @date @time 2025/6/7 10:11
     **/
    public void saveOrUpdateData(String imei, JSONObject message){
        Date date = new Date();
        String dateStr = DateUtil.dateToStr(date,DateUtil.FORMAT_4);
        //查询今日记录是否已经存在
        DeviceLocationOriginalRecord dlor = this.findOne(new Query(Criteria.where("imei").is(imei).and("date").is(dateStr)).limit(1));
        if(ObjectUtils.isEmpty(dlor)) {
            dlor = new DeviceLocationOriginalRecord();
            //保存数据
            saveData(imei, message, dlor, dateStr, date);
        } else {
            Update update = new Update();
            if(ObjectUtils.isNotEmpty(message)) {
                update.set("loc",message.toJSONString());
            }
            update.set("updateTime",date.getTime()/1000);
            this.updateById(new ObjectId(dlor.getId()),update);
        }
    }

    /**
     * @description 保存设备上报位置信息的原始数据
     * @author cwj
     * @param [imei, message]
     * @return void
     * @date @time 2025/6/20 9:23
     **/
    public void saveOriginalLocData(String imei, JSONObject message){
        Date date = new Date();
        String dateStr = DateUtil.dateToStr(date,DateUtil.FORMAT_4);
        DeviceLocationOriginalRecord dlor = new DeviceLocationOriginalRecord();
        saveData(imei, message, dlor, dateStr, date);
    }

    /**
     * @description 保存设备上报位置信息的原始数据
     * @author cwj
     * @param [imei, message, dlor, dateStr, date]
     * @return void
     * @date @time 2025/6/20 9:27
     **/
    private void saveData(String imei, JSONObject message, DeviceLocationOriginalRecord dlor, String dateStr, Date date) {
        dlor.setImei(imei);
        dlor.setDate(dateStr);
        dlor.setLoc(ObjectUtils.isNotEmpty(message)? message.toJSONString():"");
        dlor.setExpiryAt(DateUtil.getSystemExpiryAt(3));
        dlor.setCreateTime(date.getTime()/1000);
        dlor.setUpdateTime(date.getTime()/1000);
        this.save(dlor);
    }
}
